# encoding=utf-8
import os
import logging, logging.handlers
import socket

logger_ndict = {"info": logging.INFO, "error": logging.ERROR,
                "warning": logging.WARNING, "debug": logging.DEBUG, "critical": logging.CRITICAL}


class NetworkLogger():
    """create client logger

    Args:
        level (str, optional): logger level. Defaults to 'debug'.
        host (str, optional): tcp logger host. Defaults to 'localhost'.
        port (int, optional): tcp logger port. Defaults to logging.handlers.DEFAULT_TCP_LOGGING_PORT.
    
    Note:
        you must create a logger server before to use it
    """
    def __init__(self, level='debug', host='localhost', port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, timeout_seconds=3):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout_seconds)
        result = sock.connect_ex((host,int(port)))
        if result == 0:
            rootLogger = logging.getLogger()
            rootLogger.setLevel(logger_ndict[level])
            socketHandler = logging.handlers.SocketHandler(host, port)
            rootLogger.addHandler(socketHandler) 
            print("Link to {}:{} Success".format(host, port))
        else:
            raise ConnectionError("{}:{} is not running. please check it...".format(host, port))

        sock.close()
    
    def create(self, name=None):
        return logging.getLogger(name)
    

class LocalLogger(object):
    """ 本地多线程日志记录

        Args:
            log_path (str, optional): the log path root. Defaults to './'.
            app_name (str, optional): the app log name. Defaults to 'default'.
            write_level (str, optional): write to file log level. Defaults to 'debug'.
            print_level (str, optional): print to screen log level. Defaults to 'info'.
            show_info (bool, optional): show info the screen. Defaults to True.
    """
    def __init__(self, log_path='./', app_name='default', write_level='debug', print_level='info', show_info=True):
        
        # 文件的命名
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        self.logname = os.path.join(log_path, '%s.log' % (app_name))
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        # 日志输出格式
        self.formatter = logging.Formatter("[%(asctime)s - %(process)d - %(levelname)s - " + app_name + "] - %(message)s")
        self.write_level = logger_ndict[write_level]
        self.print_level = logger_ndict[print_level]
        self.show_info = show_info

    def __console(self, level, message):

        for h in self.logger.handlers:
            self.logger.removeHandler(h)
        
        # 创建一个FileHandler，用于写到本地
        fh = logging.handlers.TimedRotatingFileHandler(self.logname, when='d', interval=1, backupCount=7, encoding='utf-8')  # 这个是python3的
        fh.suffix = "%Y-%m-%d_%H-%M-%S.log"
        fh.setLevel(self.write_level)
        fh.setFormatter(self.formatter)
        self.logger.addHandler(fh)

        # 创建一个StreamHandler,用于输出到控制台
        if self.show_info:
            ch = logging.StreamHandler()
            ch.setLevel(self.print_level)
            ch.setFormatter(self.formatter)
            self.logger.addHandler(ch)

        if level == 'info':
            self.logger.info(message)
        elif level == 'debug':
            self.logger.debug(message)
        elif level == 'warning':
            self.logger.warning(message)
        elif level == 'error':
            self.logger.error(message)
       
        for h in self.logger.handlers:
            self.logger.removeHandler(h) 

    def debug(self, message):
        self.__console('debug', message)

    def info(self, message):
        self.__console('info', message)

    def warning(self, message):
        self.__console('warning', message)

    def error(self, message):
        self.__console('error', message)


if __name__ == '__main__':
    log = LocalLogger("demo", show_info=False)
    log.info("good")
